package com.kye.express.business.president_online;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.github.piasy.rxandroidaudio.AudioRecorder;
import com.github.piasy.rxandroidaudio.PlayConfig;
import com.github.piasy.rxandroidaudio.RxAmplitude;
import com.github.piasy.rxandroidaudio.RxAudioPlayer;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.databinding.FragmentPresidentOnlineAddBinding;
import com.kye.express.utils.ImageUtils;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.president_online.PresidentOnlineAddResultBean;
import com.kye.model.bean.president_online.PresidentOnlineImagesModel;
import com.kye.model.bean.president_online.PresidentOnlineListBean;
import com.kye.model.bean.president_online.PresidentOnlineResBean;
import com.kye.model.bean.president_online.RequestPresidentOnlineAddBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.IOException;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.functions.Functions;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 总裁热线--我要留言
 */
public class PresidentOnlineAddFragment extends BaseAppCompatFragment implements AudioRecorder.OnErrorListener, PresidentOnlineAddFragmentContract.PresidentOnlineAddView {
    private static final String ARG_DATA = "data";
    private final int MAX_TEXT_SIZE = 500;//文本最大输入字数
    private final int REQUEST_CODE_CHOOSE = 1;//相机Requset
    private boolean mIsTextLeveType = true;//留言类型，语音留言/文本留言（默认为文字）
    private FragmentPresidentOnlineAddBinding mBinding;
    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private boolean isEdit = false;//图片可以编辑
    protected PresidentOnlineAddFragmentContract.PresidentOnlineAddViewPresenter mPresenter;
    private Dialog kyeLoadingDialog;
    private int mMessageClass = -1;//留言类别：1时效，2 服务，3 安全，4 建议，5 其他
    private PresidentOnlineListBean.DatasBean mEditData;

    public static PresidentOnlineAddFragment newInstance(PresidentOnlineListBean.DatasBean datasBean) {
        PresidentOnlineAddFragment fragment = new PresidentOnlineAddFragment();
        if (datasBean != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(ARG_DATA, datasBean);
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_president_online_add, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = FragmentPresidentOnlineAddBinding.bind(view);
        mPresenter = new PresidentOnlineAddFragmentContract.PresidentOnlineAddViewPresenter(getActivity());
        mPresenter.bind(this);
        getActivity().setTitle(getString(R.string.president_online_add_message));
        initView();
        initEvent();
        initRecorder();
    }

    private void initView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mEditData = (PresidentOnlineListBean.DatasBean) bundle.getSerializable(ARG_DATA);
        }
        mPermissions = new RxPermissions(getActivity());
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(PresidentOnlineImagesModel.class, new PresidentOnlineImagetemViewBinder(getActivity()));
        mBinding.recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        setUpViewByData();
    }

    private void setUpViewByData() {
        if (mEditData != null) {
            mBinding.rlSelectType.setEnabled(true);
            mBinding.tvMsgType.setText(mEditData.getMessageClass());

            if (!TextUtils.isEmpty(mEditData.getMessage())) {
                mBinding.leaveWordsFetWords.setText(mEditData.getMessage());
                mBinding.leaveWordsFetWords.setSelection(mEditData.getMessage().length());
            }

            //  编辑状态
            mBinding.tvLeaveChangeMethod.setVisibility(View.GONE);
            mBinding.ivSelectMsgType.setVisibility(View.VISIBLE);
            if (mEditData.isIsImage()) {
                mPresenter.loadResDatas(mEditData.getGuid(), "0");
                mBinding.tvLeaveUpload.setText(getString(R.string.president_online_preview_image));
                mBinding.ivLeavePhoto.setVisibility(View.GONE);
                mBinding.recyclerview.setVisibility(View.GONE);
                mBinding.llPicContainer.setVisibility(View.VISIBLE);
                mBinding.tvLeaveEdit.setVisibility(View.GONE);
            } else {
                mBinding.relatPicgroup.setVisibility(View.GONE);
            }
        } else {
            new MaterialDialog.Builder(getActivity())
                    .title(getString(R.string.common_reminder))
                    .content(R.string.president_online_add_dialog_message_tips)
                    .positiveText(R.string.common_know)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    }

    private void initEvent() {

        RxView.clicks(mBinding.rlSelectType)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        new MaterialDialog.Builder(getActivity())
                                .items(getResources().getStringArray(R.array.president_online_leave_type))
                                .itemsCallback(new MaterialDialog.ListCallback() {
                                    @Override
                                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                        mBinding.tvMsgType.setText(text.toString());
                                        mMessageClass = position + 1;
                                    }
                                })
                                .show();
                    }
                });

        RxView.clicks(mBinding.tvLeaveChangeMethod)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        onLeaveTypeChanged();
                    }
                });

        RxView.clicks(mBinding.voiceView.tvLeaveDel)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        new MaterialDialog.Builder(getActivity())
                                .title(R.string.common_reminder)
                                .content(R.string.president_online_confirm_delete_voice)
                                .positiveText(R.string.common_confirm)
                                .negativeText(R.string.common_cancel)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        //TODO 删除文件
                                        mAudioFile = null;
                                        updateRecordUI(false);
                                    }
                                }).onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                                .show();
                    }
                });

        RxView.clicks(mBinding.voiceView.relatTrialStart)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startPlay();
                    }
                });

        RxView.clicks(mBinding.ivLeavePhoto)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mDatas.size() >= 3) {
                            ToastManager.show(getActivity(), R.string.president_online_max_image_size, Toast.LENGTH_SHORT);
                        } else {
                            boolean isPermissionsGranted
                                    = mPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    && mPermissions.isGranted(Manifest.permission.CAMERA);
                            if (!isPermissionsGranted) {
                                mPermissions
                                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                        .subscribe(granted -> {
                                            if (granted) {
                                                selectPhotos();
                                            } else {
                                                ToastManager.show(getActivity(), R.string.president_online_no_permissions_storage,
                                                        Toast.LENGTH_SHORT);
                                            }
                                        }, Throwable::printStackTrace);
                            } else {
                                selectPhotos();
                            }
                        }
                    }
                });

        RxView.clicks(mBinding.tvLeaveEdit)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (isEdit) {
                            mBinding.tvLeaveEdit.setText(getString(R.string.common_edit));
                        } else {
                            mBinding.tvLeaveEdit.setText(getString(R.string.common_cancel));
                        }
                        updateEditStatus();
                        isEdit = !isEdit;
                    }
                });

        RxView.clicks(mBinding.btnSubmit)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (checkParams()) {
                            new MaterialDialog.Builder(getActivity())
                                    .title(R.string.common_reminder)
                                    .content(R.string.president_online_is_commit_message)
                                    .positiveText(R.string.common_confirm)
                                    .negativeText(R.string.common_cancel)
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            mPresenter.onUser();
                                        }
                                    }).onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                }
                            })
                                    .show();
                        }
                    }
                });
    }

    private void updateEditStatus() {
        List<PresidentOnlineImagesModel> datas = (List<PresidentOnlineImagesModel>) mAdapter.getItems();
        if (datas != null) {
            for (PresidentOnlineImagesModel imagesModel : datas) {
                if (isEdit) {
                    imagesModel.setShowDelete(false);
                } else {
                    imagesModel.setShowDelete(true);
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    private void selectPhotos() {
        Matisse.from(this)
                .choose(MimeType.ofAll(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, getActivity().getApplication().getPackageName() + ".fileprovider"))
                .maxSelectable(3)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == getActivity().RESULT_OK) {
            List<String> pathResult = Matisse.obtainPathResult(data);
            if (pathResult != null && pathResult.size() > 0) {
                addImageDatasAfterSelected(pathResult);
            }
        }
    }

    private void addImageDatasAfterSelected(List<String> pathResult) {
        for (String item : pathResult) {
            mDatas.add(new PresidentOnlineImagesModel(item, false));
        }
        mAdapter.notifyDataSetChanged();
    }


    private void onLeaveTypeChanged() {
        if (mIsTextLeveType) {
            mBinding.tvLeaveChangeMethod.setText(getString(R.string.president_online_add_text_message));
            mBinding.leaveWordsFetWords.setVisibility(View.GONE);
            mBinding.tvTextNumber.setVisibility(View.GONE);
            mBinding.voiceView.rlLeaveVoice.setVisibility(View.VISIBLE);
        } else {
            mBinding.tvLeaveChangeMethod.setText(getString(R.string.president_online_add_voice_message));
            mBinding.leaveWordsFetWords.setVisibility(View.VISIBLE);
            mBinding.tvTextNumber.setVisibility(View.VISIBLE);
            mBinding.voiceView.rlLeaveVoice.setVisibility(View.GONE);
        }
        mIsTextLeveType = !mIsTextLeveType;
    }

    @Override
    public void onComplete() {
        if (kyeLoadingDialog != null && kyeLoadingDialog.isShowing()) {
            kyeLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        if (kyeLoadingDialog == null) {
            kyeLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                    .build();
        }
        kyeLoadingDialog.show();
    }

    @Override
    public void onLoaded(PresidentOnlineAddResultBean datas) {
        ToastManager.show(getActivity(), R.string.president_online_commit_success, Toast.LENGTH_SHORT);
        if (kyeLoadingDialog != null && kyeLoadingDialog.isShowing()) {
            kyeLoadingDialog.dismiss();
        }
        getActivity().onBackPressed();
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (kyeLoadingDialog != null && kyeLoadingDialog.isShowing()) {
            kyeLoadingDialog.dismiss();
        }
    }

    @Override
    public void onUser(User user) {
        if (user != null && !TextUtils.isEmpty(user.getToken())) {
            RequestPresidentOnlineAddBean requestPresidentOnlineAddBean = new RequestPresidentOnlineAddBean();
            if (!mIsTextLeveType) {
                requestPresidentOnlineAddBean.setAudio(mAudioFile.getAbsolutePath());
                requestPresidentOnlineAddBean.setAudioSize(mCurrentRecordMis + "");
            }
            requestPresidentOnlineAddBean.setMessage(StringUtils.getReplaceStr(mBinding.leaveWordsFetWords.getText().toString().trim()));

            requestPresidentOnlineAddBean.setMessageType(mIsTextLeveType ? 1 : 2);
            if (mEditData != null) {
                requestPresidentOnlineAddBean.setOperationType(1);
                requestPresidentOnlineAddBean.setCode(mEditData.getCode());
                if (mMessageClass == -1) {
                    requestPresidentOnlineAddBean.setMessageClass(getMessageClassIndex(mEditData.getMessageClass()));
                } else {
                    requestPresidentOnlineAddBean.setMessageClass(mMessageClass);
                }
            } else {
                requestPresidentOnlineAddBean.setOperationType(0);
                requestPresidentOnlineAddBean.setMessageClass(mMessageClass);
            }
            mPresenter.loadDatas(requestPresidentOnlineAddBean, (List<PresidentOnlineImagesModel>) mAdapter.getItems());
        } else {
            LoginActivity.startActivity(getActivity());
        }
    }

    @Override
    public void onCompleteRes() {

    }

    @Override
    public void onLoadingRes() {

    }

    @Override
    public void onLoadedRes(PresidentOnlineResBean bean) {
        //  图片
        List<String> images = bean.getPicture();
        if (images != null) {
            for (int i = 0; i < images.size(); i++) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ScreenUtils.dp2px(getActivity(), 65), ScreenUtils.dp2px(getActivity(), 65));
                final ImageView photoView = new ImageView(getActivity());
                params.rightMargin = ScreenUtils.dp2px(getActivity(), 10);
                photoView.setLayoutParams(params);
                photoView.setScaleType(ImageView.ScaleType.FIT_XY);
                final Bitmap bitmap = ImageUtils.Base64StringToBitmap(images.get(i));
                if (bitmap != null) {
                    photoView.setImageBitmap(bitmap);
                    photoView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                }
                mBinding.llPicContainer.addView(photoView);
            }
        }
    }

    @Override
    public void onErrorRes(String msg) {

    }

    private int getMessageClassIndex(String messageClass) {
        if ("时效".equals(messageClass)) {
            return 1;
        } else if ("服务".equals(messageClass)) {
            return 2;
        } else if ("安全".equals(messageClass)) {
            return 3;
        } else if ("建议".equals(messageClass)) {
            return 4;
        } else if ("其他".equals(messageClass)) {
            return 5;
        }
        return -1;
    }

    private boolean checkParams() {
        String leaveType = mBinding.tvMsgType.getText().toString();
        if (TextUtils.isEmpty(leaveType) || leaveType.equals(getString(R.string.president_online_hint_message_type))) {
            ToastManager.show(getActivity(), getString(R.string.president_online_hint_message_type), Toast.LENGTH_SHORT);
            return false;
        }
        if (mIsTextLeveType) {
            String content = StringUtils.getReplaceStr(mBinding.leaveWordsFetWords.getText().toString().trim());
            if (TextUtils.isEmpty(content)) {
                ToastManager.show(getActivity(), R.string.president_online_message_null, Toast.LENGTH_SHORT);
                return false;
            }

            //  不允许提交全数字
            if (StringUtils.isNumeric(content)) {
                ToastManager.show(getActivity(), R.string.president_online_message_is_all_numeric, Toast.LENGTH_SHORT);
                return false;
            }

            //   不允许提交全字母
            if (StringUtils.isChart(content)) {
                ToastManager.show(getActivity(), R.string.president_online_message_is_all_chart, Toast.LENGTH_SHORT);
                return false;
            }
        } else {
            if (mAudioFile == null) {
                ToastManager.show(getActivity(), R.string.president_online_no_voice, Toast.LENGTH_SHORT);
                return false;
            }
        }
        return true;
    }

    //============录音部分start============================
    private final int MIN_RECORD_TIME = 3;//最小录音时间
    private final int MAX_RECORD_TIME = 60;//最大录音时间
    private AudioRecorder mAudioRecorder;
    private RxAudioPlayer mRxAudioPlayer;
    private File mAudioFile;
    private Disposable mRecordDisposable;
    private RxPermissions mPermissions;
    private int mCurrentRecordMis = 0;

    private void initRecorder() {
        mAudioRecorder = AudioRecorder.getInstance();
        mRxAudioPlayer = RxAudioPlayer.getInstance();
        mAudioRecorder.setOnErrorListener(this);

        mBinding.voiceView.btnLeaveRecord.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mBinding.voiceView.ivLeaveMic.start(R.drawable.president_online_leave_recording);
                    press2Record();
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    mBinding.voiceView.ivLeaveMic.stop(R.mipmap.recording4);
                    release2Send();
                    break;
                default:
                    break;
            }

            return true;
        });

    }

    private void press2Record() {
        boolean isPermissionsGranted
                = mPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && mPermissions.isGranted(Manifest.permission.RECORD_AUDIO);
        if (!isPermissionsGranted) {
            mPermissions
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO)
                    .subscribe(granted -> {
                        // not record first time to request permission
                        if (granted) {
                            ToastManager.show(getActivity(), R.string.president_online_rerecord,
                                    Toast.LENGTH_SHORT);
                        } else {
                            ToastManager.show(getActivity(), R.string.president_online_no_permissions,
                                    Toast.LENGTH_SHORT);
                        }
                    }, Throwable::printStackTrace);
        } else {
            stopPlay();
            recordAfterPermissionGranted();
        }
    }

    private void recordAfterPermissionGranted() {
        if (initOutputFile()) {
            mRecordDisposable = Observable
                    .fromCallable(() -> {
                        return mAudioRecorder.prepareRecord(MediaRecorder.AudioSource.MIC,
                                MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.AudioEncoder.AAC,
                                192000, 192000, mAudioFile);
                    })
                    .doOnComplete(() -> {
                        mAudioRecorder.startRecord();
                    })
                    .flatMap(o -> RxAmplitude.from(mAudioRecorder))
                    .compose(bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(level -> {
                        int progress = mAudioRecorder.progress();
                        if (progress >= MAX_RECORD_TIME) {
                            release2Send();
                        }
                    }, Throwable::printStackTrace);
        } else {
            Logger.e("录音文件创建失败");
        }
    }

    private void release2Send() {
        if (mRecordDisposable != null && !mRecordDisposable.isDisposed()) {
            mRecordDisposable.dispose();
            mRecordDisposable = null;
        }
        Observable
                .fromCallable(() -> {
                    int seconds = mAudioRecorder.stopRecord();
                    if (seconds < MIN_RECORD_TIME) {
                        mAudioFile = null;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastManager.show(getActivity(), String.format(getString(R.string.president_online_record_time_min), MIN_RECORD_TIME), Toast.LENGTH_SHORT);
                            }
                        });
                        return false;
                    }
                    mCurrentRecordMis = seconds;
                    return true;
                })
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(added -> {
                    if (added) {
                        updateRecordUI(true);
                    }
                }, Throwable::printStackTrace);
    }

    public void startPlay() {
        if (mAudioFile != null && mRxAudioPlayer != null) {
            if (mRxAudioPlayer.getMediaPlayer() != null && mRxAudioPlayer.getMediaPlayer().isPlaying()) {
                stopPlay();
            } else {
                mBinding.voiceView.ivVoicetrialSmall.start(R.drawable.president_online_voice_sound);
                mRxAudioPlayer.play(
                        PlayConfig.file(mAudioFile)
                                .looping(false)
                                .streamType(AudioManager.STREAM_VOICE_CALL)
                                .build())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(final Disposable disposable) {

                            }

                            @Override
                            public void onNext(final Boolean aBoolean) {
                                // prepared
                            }

                            @Override
                            public void onError(final Throwable throwable) {
                                mBinding.voiceView.ivVoicetrialSmall.stop(R.mipmap.sounds3);
                            }

                            @Override
                            public void onComplete() {
                                mBinding.voiceView.ivVoicetrialSmall.stop(R.mipmap.sounds3);
                            }
                        });
            }
        }
    }

    public void stopPlay() {
        if (mRxAudioPlayer != null) {
            mRxAudioPlayer.stopPlay();
        }
        mBinding.voiceView.ivVoicetrialSmall.stop(R.mipmap.sounds3);
    }

    @Override
    public void onError(int error) {
        mAudioFile = null;
        if (mAudioRecorder != null) {
            mAudioRecorder.stopRecord();
        }
        stopPlay();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastManager.show(getActivity(), R.string.president_online_record_error,
                        Toast.LENGTH_SHORT);
            }
        });
        Logger.e("录音出现错误,error code====" + error);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRxAudioPlayer != null) {
            mRxAudioPlayer.stopPlay();
        }
        mPresenter.unbind();
    }

    private boolean initOutputFile() {
        File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + Constants.SDCARD_FOLDER_NAME);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        mAudioFile = new File(fileDir, "presidentonlinevoice.file.m4a");
        if (!mAudioFile.exists()) {
            try {
                mAudioFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 刷新录音结束UI显示
     */
    private void updateRecordUI(boolean showResult) {
        if (showResult) {
            int tempWidth = computeWith();
            ViewGroup.LayoutParams layoutParams = mBinding.voiceView.relatTrialStart.getLayoutParams();
            layoutParams.width = tempWidth;
            mBinding.voiceView.relatTrialStart.setLayoutParams(layoutParams);

            mBinding.voiceView.ivLeaveMic.setVisibility(View.GONE);
            mBinding.voiceView.btnLeaveRecord.setVisibility(View.GONE);
            mBinding.voiceView.relatVoiceTrial.setVisibility(View.VISIBLE);
            mBinding.voiceView.tvLeaveTime.setText(mCurrentRecordMis + "\"");
        } else {
            mBinding.voiceView.ivLeaveMic.setVisibility(View.VISIBLE);
            mBinding.voiceView.btnLeaveRecord.setVisibility(View.VISIBLE);
            mBinding.voiceView.relatVoiceTrial.setVisibility(View.GONE);
        }
    }

    /**
     * 计算语音显示view的宽度
     */
    private int computeWith() {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        mBinding.voiceView.tvLeaveTrial.measure(w, h);
        mBinding.voiceView.tvLeaveDel.measure(w, h);

        int mRelatleaveWidh = ScreenUtils.getScreenWidth();
        int paddingLeft = mBinding.voiceView.relatVoiceTrial.getPaddingLeft();
        int paddingRight = mBinding.voiceView.relatVoiceTrial.getPaddingRight();
        int mMixWith = ScreenUtils.dp2px(getActivity(), 100);

        int mTvRialTextWidh = mBinding.voiceView.tvLeaveTrial.getMeasuredWidth();

        int mTvDeleteWidth = mBinding.voiceView.tvLeaveDel.getMeasuredWidth();
        int delPaddingLeft = mBinding.voiceView.tvLeaveDel.getPaddingLeft();
        int delPaddingRight = mBinding.voiceView.tvLeaveDel.getPaddingRight();

        int maxWith = mRelatleaveWidh - paddingLeft - paddingRight - mTvRialTextWidh - mTvDeleteWidth - ScreenUtils.dp2px(getActivity(), 25) - delPaddingLeft - delPaddingRight;

        int tempWidth = (int) (Double.parseDouble(mCurrentRecordMis + "") / Double.parseDouble(MAX_RECORD_TIME + "") * maxWith);

        if (tempWidth < mMixWith) {
            tempWidth = mMixWith;
        }
        if (tempWidth > maxWith) {
            tempWidth = maxWith;
        }
        return tempWidth;
    }

    //============录音部分end============================

}
